<template>
  <!-- 主播管理 -->
  <a-spin class="anchor-review" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter new-filter">
      <div class="l search-box-item">
        <!-- 站点、高德ID、门店地址、门店名称、POI审核状态 -->
        <div>
          <span class="label-text-small">站点选择：</span>
          <a-select class="search-width-small" show-search :allowClear="true" placeholder="选择站点" v-model="search.locationName" @change="handleByQueryCond" :filter-option="filterOption">
            <a-select-option v-for="(item, index) in locationListData" :key="index + '-' + item.id" :value="item.city">{{ item.city }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span class="label-text-small">高德ID：</span>
          <a-input-search class="search-width-small" type="text" placeholder="高德ID" allowClear v-model="search.gdId" @search="handleByQueryCond" />
        </div>
        <div>
          <span class="label-text-small">门店地址：</span>
          <a-input-search class="search-width-small" type="text" placeholder="地址" allowClear v-model="search.address" @search="handleByQueryCond" />
        </div>
        <div>
          <span class="label-text-small">门店名称：</span>
          <a-input-search class="search-width-small" type="text" placeholder="门店名称" allowClear v-model="search.name" @search="handleByQueryCond" />
        </div>
        <div>
          <span class="label-text-small">POI审核状态：</span>
          <a-select class="search-width-small" placeholder="请选择状态" v-model="search.matchStatus" @change="handleByQueryCond">
            <a-select-option v-for="item in matchStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
      </div>
      <div class="search-new-r">
        <a-button type="primary" @click="handleByQueryCond" style="background:#1d6fe9">查询</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body">
      <a-table :columns="tableColumns" :pagination="false" :data-source="poiList" :scroll="{ x: 900, y: tableHeight }" rowKey="id">
        <!-- 高德POI信息：门店名称、所属城市、门店地址、经度、纬度、高德POI_ID -->
        <template slot="poiName" slot-scope="text, record">
          <p><span class="font-weight-bold">门店名称：</span>{{ record.poiName || '无' }}</p>
          <p><span class="font-weight-bold">所属城市：</span>{{ record.poiCity || '无' }}</p>
          <p><span class="font-weight-bold">门店地址：</span>{{ record.poiAddress || '无' }}</p>
          <p><span class="font-weight-bold">经度：</span>{{ record.poiLongitude || '无' }}</p>
          <p><span class="font-weight-bold">纬度：</span>{{ record.poiLatitude || '无' }}</p>
          <p v-if="record.gdId">
            <span class="font-weight-bold">高德POI_ID：</span><a :href="record.gdUrl || ''" target="_blank" v-if="record.gdUrl">{{ record.gdId || '' }}</a
            ><span v-else>{{ record.gdId || '无' }}</span>
          </p>
        </template>
        <!-- 快手POI融合信息：POI申请时间、POI审核状态(1/2/3/4/5)、快手POI_ID、已绑定SPU：XX,XXX、POI品质、POI等级、备注 -->
        <template slot="applyTime" slot-scope="text, record">
          <div style="display:flex;">
            <div style="padding-right:10px;border-right:1px dotted #ccc;width:235px;">
              <p><span class="font-weight-bold">POI申请时间：</span>{{ record.applyTime || '无' }}</p>
              <p><span class="font-weight-bold">POI审核状态：</span>{{ record.matchStatusStr || '无' }}</p>
              <p><span class="font-weight-bold">快手POI_ID：</span>{{ record.kwaiPoiId || '无' }}</p>
              <p><span class="font-weight-bold">已绑定SPU：</span>{{ record.bindProds || '无' }}</p>
            </div>
            <div style="padding-left:10px;">
              <p><span class="font-weight-bold">POI品质：</span>{{ record.kwaiPoiQuality.length > 0 ? record.kwaiPoiQuality.join() : '无' }}</p>
              <p><span class="font-weight-bold">POI等级：</span>{{ record.kwaiPoiGrade || '无' }}</p>
              <p><span class="font-weight-bold">备注：</span>{{ record.matchStatusDesc || '无' }}</p>
            </div>
          </div>
        </template>
        <template slot="action" slot-scope="text, record">
          <!-- 获取快手POI(matchStatus=4/5显示,调快手融合接口 /merge) -->
          <a-button v-if="!record.kwaiPoiId && record.gdId" type="link" href="javascript:;" size="small" @click="refreshStatus(record.gdId)">获取快手POI</a-button>
          <!-- 申请挂载(0/3显示 mount/poi)、 -->
          <a-button v-if="(record.matchStatus === 0 || record.matchStatus === 3) && record.kwaiPoiId" type="link" href="javascript:;" size="small" @click="submitSpu(record.kwaiPoiId)"
            >提交快手审核</a-button
          >
          <a-button type="link" v-if="record.matchStatus === 2 && record.kwaiPoiId" href="javascript:;" size="small" @click="updateSpu(record.kwaiPoiId)">修改快手poi标签</a-button>
          <!-- “SPU信息” -->
          <a-button type="link" href="javascript:;" v-if="record.kwaiPoiId" size="small" @click="toSpuList(record.kwaiPoiId)">SPU信息</a-button>
          <!-- 高德刷新 -->
          <a-button type="link" v-if="record.gdId" href="javascript:;" size="small" @click="gdUpdate(record)">高德更新</a-button>
          <!-- 查询快手审核 -->
          <a-button type="link" v-if="record.kwaiPoiId" href="javascript:;" size="small" @click="ksUpdate(record)">查询快手审核</a-button>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="search.pageSize"
        v-model="search.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
    <quality-submit
      v-model="isShowQuality"
      :qualityList="qualityList"
      :postQualityList="postQualityList"
      :getProductItemId="productItemId"
      :gradeList="gradeList"
      :poiIds="poiIds"
      @onCancel="handleCloseQuality"
      @callback="afterSubmit"
      :type="3"
      :typeThree="typeThree"
    ></quality-submit>
  </a-spin>
</template>

<script>
import { pointLocationList, poiRefreshGdPoi } from '@/service'
import { kwaiPoiList, kwaiPoiMount, kwaiPoiqualityGet, kwaiPoiGetId } from '@/service/ksService'
import moment from 'moment'
import { columnsConfig } from './columns'
import debounce from 'lodash/debounce'
import qualitySubmit from './components/qualitySubmit'
export default {
  name: 'ksPoiList',
  data() {
    this.getLocationList = debounce(this.getLocationList, 800)
    return {
      moment,
      // loading是否显示
      isLoading: false,
      pagination: {
        total: 0
      },
      // table数据查询条件
      search: {
        gdId: '',
        matchStatus: '',
        address: '',
        name: '',
        locationName: undefined,
        pageIndex: 1,
        pageSize: 10
      },
      // poi列表
      poiList: [],
      tableColumns: columnsConfig.poiColumns || [],
      locationListData: [],
      isApplyMaterial: false,
      isShowQuality: false,
      qualityList: [],
      postQualityList: [],
      productItemId: [],
      gradeList: [],
      poiIds: [],
      typeThree: 1
    }
  },
  components: {
    qualitySubmit
  },
  computed: {
    matchStatus() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '待申请',
          value: 0
        },
        {
          name: '挂载中',
          value: 1
        },
        {
          name: '挂载成功',
          value: 2
        },
        {
          name: '挂载失败',
          value: 3
        },
        {
          name: '匹配失败',
          value: 4
        },
        {
          name: '融合失败',
          value: 5
        }
      ]
    }
  },

  methods: {
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.search.pageIndex = 1
      this.setPath(this.getParams())
      this.query()
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    // 站点列表
    async getLocationList() {
      await pointLocationList({ city: '' }).then((res = []) => {
        this.locationListData = res
      })
    },
    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.search.pageIndex = num
      this.setPath(this.getParams())
      this.query()
    },

    // 拿参数
    getParams() {
      // const { pageIndex, pageSize } = this.pagination
      const { address, name, gdId, locationName, matchStatus, pageIndex, pageSize } = this.search

      return {
        pageIndex,
        pageSize,
        gdId,
        locationName,
        address,
        name,
        matchStatus
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, gdId, matchStatus, locationName, address, name } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          gdId: gdId || '',
          matchStatus: isNaN(matchStatus) ? '' : matchStatus === 0 ? '0' : +matchStatus,
          locationName: locationName || '',
          address: address || '',
          name: name || ''
        }
        console.log(this.search)
      }
    },
    // 初始化
    initQuery() {
      // this.pagination.pageIndex = 1
      this.search.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },

    /**
     * 获取poi信息列表
     * @returns {Promise<void>}
     */
    query() {
      this.isLoading = true
      kwaiPoiList(this.getParams())
        .then((rs) => {
          this.poiList = Object.freeze(rs.poiList) || []
          this.pagination.total = rs.total || 0
          this.isApplyMaterial = rs.isApplyMaterial
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key] || origin[key] === 0) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    // 获取快手POI
    refreshStatus(gdId = '') {
      this.isLoading = true
      kwaiPoiGetId({ gdId })
        .then((res) => {
          this.$messageSend.success('刷新成功')
        })
        .finally(() => {
          this.query()
          this.isLoading = false
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    // 套餐提交快手审核
    submitSpu(id = '') {
      this.getPoiQualityGrade(id).then(() => {
        this.typeThree = 1
        this.isShowQuality = true
      })
    },
    // 修改套餐提交快手审核
    updateSpu(id = '') {
      this.getPoiQualityGrade(id).then(() => {
        this.typeThree = 2
        this.isShowQuality = true
      })
    },
    // Poi品质等级获取
    getPoiQualityGrade(kwaiPoiId = '') {
      return new Promise((resolve, reject) => {
        kwaiPoiqualityGet({ poiId: kwaiPoiId }).then((res) => {
          const { gradeList = [], qualityLabels = [] } = res
          const self = this
          this.$nextTick(() => {
            this.gradeList = gradeList
            this.qualityList = qualityLabels
            this.poiIds = [kwaiPoiId]
            qualityLabels.forEach((item) => {
              if (item.status === 1) {
                self.postQualityList.push(item.type)
              }
            })
            resolve(true)
          })
        })
      })
    },
    handleCloseQuality() {
      this.isShowQuality = false
      this.productItemId = 0
      this.gradeList = []
      this.postQualityList = []
      this.qualityList = []
      this.typeThree = 1
    },
    afterSubmit() {
      this.query()
      this.$messageSend.success('操作成功')
      this.handleCloseQuality()
    },
    // 打开POI所绑定的SPU列表信息
    toSpuList(kwaiPoiId = '') {
      // 外部商户ID
      this.$router.push({
        path: '/kwaiManage/spuInfoForPoi',
        query: {
          kwaiPoiId
        }
      })
    },
    // 高德刷新
    gdUpdate(row = {}) {
      const { id = '' } = row
      this.isLoading = true
      poiRefreshGdPoi({ id })
        .then((res) => {
          this.$messageSend.success('操作成功')
        })
        .finally(() => {
          this.query()
          this.isLoading = false
        })
        .catch(() => {
          this.isLoading = false
        })
    },
    // 快手刷新
    ksUpdate(row = {}) {
      const { kwaiPoiId = '' } = row
      this.isLoading = true
      kwaiPoiMount({ poiId: kwaiPoiId })
        .then((res) => {
          this.$messageSend.success('操作成功')
        })
        .finally(() => {
          this.query()
          this.isLoading = false
        })
        .catch(() => {
          this.isLoading = false
        })
    }
  },

  mounted() {
    this.getLocationList()
    this.setSearch()
    this.initQuery()
  }
}
</script>

<style lang="less" scoped>
ul {
  padding-inline-start: 0;
  margin-bottom: 0;
}
.ant-col-7 {
  text-align: right;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}

.ant-form-item {
  margin: 10px 0 0;
}

p {
  margin-bottom: 5px;
  font-size: 13px;
}
.font-weight-bold {
  font-weight: bold;
  display: inline-block;
}

table tbody td div {
  margin-top: 2px;
}
/deep/ table tbody td a {
  margin-right: 0;
}
</style>
